package com.mazaiting.redeye.module.splash

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity;
import com.mazaiting.easy.app.IApplicationComponent
import com.mazaiting.easy.base.activity.BaseActivity
import com.mazaiting.easy.base.activity.BaseLoadingActivity
import com.mazaiting.log.L
import com.mazaiting.redeye.BuildConfig
import com.mazaiting.redeye.R
import com.mazaiting.redeye.api.UserApi
import com.mazaiting.redeye.base.ApplicationComponentImpl
import com.mazaiting.redeye.module.main.MainActivity
import com.mazaiting.redeye.module.user.login.LoginActivity
import com.mazaiting.redeye.utils.SignUtil

import java.util.*

/**
 * 开屏页
 */
class SplashActivity : BaseLoadingActivity<SplashPresenter>(), SplashContract.View {
    override fun getContentLayout(): Int = R.layout.activity_splash

    override fun inject(applicationComponent: IApplicationComponent?) {
        DaggerSplashComponent
            .builder()
            .applicationComponentImpl(applicationComponent as ApplicationComponentImpl)
            .build()
            .inject(this)
    }

    override fun initData() {
        if (presenter!!.checkPublicKey()) {
            // 获取公钥
            presenter?.publicKey()
        }
    }

    override fun isSlideLock(): Boolean = true

    override fun bindView(view: View?, savedInstanceState: Bundle?) {
        super.bindView(view, savedInstanceState)
        // 获取 TextView
        val tvTime = findViewById<TextView>(R.id.splash_tv_time)
        // 创建定时器
        val timer = Timer()
        var time = 5
        // 定时器时间
        if (BuildConfig.DEBUG) {
            time = 1
        }
        // 每隔 1 秒执行
        timer.schedule(object : TimerTask() {
            override fun run() {
                runOnUiThread {
                    // 设置格式
                    tvTime.text = String.format(getString(R.string.remain_time), --time)
                    // 时间结束之后，开启新页面，并结束定时器
                    if (0 == time) {
                        // 取消定时器
                        timer.cancel()
//                        Toast.makeText(this@SplashActivity, "定时器结束", Toast.LENGTH_SHORT).show()
                        startLoginOrMain()
                    }
                }
            }
        }, 0, 1000)
    }

    /**
     * 开启登录页或主页
     */
    private fun startLoginOrMain() {
        val intent = Intent()
        if (null != presenter) {
            // 检测是否登录
            if (presenter!!.checkLogin()) {
                intent.setClass(this@SplashActivity, MainActivity::class.java)
            } else {
                intent.setClass(this@SplashActivity, LoginActivity::class.java)
            }
        } else {
            intent.setClass(this@SplashActivity, LoginActivity::class.java)
        }
        startActivity(intent)
        finish()
    }
}